
import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME
} from '@/config/app';
import {
	toLogin,
	checkLogin
} from '../libs/login';
import store from '../store';


/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}) {
	let Url = HTTP_REQUEST_URL,
		header = HEADER;
	console.log(url+'---------------------------')
	if (!noAuth) {
		//登录过期自动登录
		console.log(url+'未登录----------------------')
		if (!store.state.app.token && !checkLogin()) {
			toLogin();
			return Promise.reject({
				msg: '未登录'
			});
		}
	}
	// console.log('header',header)
	if (store.state.app.token) header[TOKENNAME] = 'Bearer ' + store.state.app.token;
	
	console.log('store.state.app.location',store.state.app.location)
	if(store.state.app.location){
		data = {
			...data,
			lat:store.state.app.location.latitude,
			lng:store.state.app.location.longitude
		}
	}
	console.log(url+'请求参数',data)
	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + '/api/' + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				console.log(url+'请求结果',res)
				if (noVerify){
					console.log(1)
					reslove(res.data, res);
				}
					
				else if (res.data.status == 200){
					console.log(2)
					reslove(res.data, res);
				}
					
				else if ([410000, 410001, 410002].indexOf(res.data.status) !== -1) {
					toLogin();
					reject(res.data);
				} else if (res.data.status == 410010) {
					console.log(3)
					uni.showModal({
						title: '提示',
						content: res.data.msg,
						showCancel: false,
						confirmText: '我知道了'
					});
				} else{
		
					
					reject(res.data.msg || '系统错误');
				}
				
			},
			fail: (msg) => {
				console.log(url+'请求结果',msg)
				let data = {
					mag: '请求失败',
					status: 1 //1没网
				}
				// #ifdef APP-PLUS
				reject(data);
				// #endif
				// #ifndef APP-PLUS
				reject('请求失败');
				// #endif
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;
